package com.nisure.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nisure.common.GetRemoteApiUtils;
import com.nisure.common.R;
import com.nisure.entity.KeywordBackupEntity;
import com.nisure.entity.KeywordEntity;
import com.nisure.entity.MaterialEntity;
import com.nisure.entity.OriginBaiduEntity;
import com.nisure.info.KeywordTypeInfo;
import com.nisure.service.CompanyBackupService;
import com.nisure.type.KeywordType;
import com.nisure.ws.remoteinfo.MaterialCreateInfo;
import com.nisure.ws.remoteinfo.RemoteIndustryInfo;
import com.nisure.ws.service.ManageIndustryService;
import com.nisure.ws.service.MaterialService;

@RestController
@RequestMapping("/material")
public class MaterialController {

	@Autowired
	private com.nisure.service.MaterialService materialService;
	@Autowired
	private CampaignController campaignController;
	@Autowired
	private AccountController accountController;
	@Autowired
	private AdgroupController adgroupController;
	@Autowired
	private KeywordController keywordController;

	// 加载全部行业用于下拉框
	@RequestMapping("/getIndustries")
	public R getIndustries() {
		ManageIndustryService manageIndustryService = GetRemoteApiUtils
				.getRemoteService(ManageIndustryService.class,
						"manageIndustryService");
		List<RemoteIndustryInfo> industryList = manageIndustryService
				.getALLIndustryList();
		return R.ok().put("industryList", industryList);

	}

	// 获取物料生成
	@RequestMapping("/getMaterial")
	public R getMaterial(@RequestParam Map<String, Object> params,HttpServletRequest request) {
		// String coreKeyword = (String) params.get("coreKeyword");
		String keywordstr = (String) request.getSession().getAttribute("keywordstr");
		String[] coreKeywords = keywordstr.split(",");
		String inversestr = (String) request.getSession().getAttribute("inversestr");
		String industryId = null;
		if(!request.getSession().getAttribute("industryId").equals("全部行业")){
			industryId = (String) request.getSession().getAttribute("industryId");
		}
		
		if (coreKeywords == null) {
			return R.error().error("行业或者核心关键词获取失败！");
		}
		MaterialService materialService = GetRemoteApiUtils.getRemoteService(
				MaterialService.class, "materialService");
		List<MaterialCreateInfo> materialList = new ArrayList<MaterialCreateInfo>();
		for (String coreKeyword : coreKeywords) {
			if (coreKeyword != null || coreKeyword != "") {
				materialList.addAll(materialService.listMaterial(industryId,
						coreKeyword, inversestr));
			}

		}
		if (materialList.size() == 1) {
			return R.ok().put("materialList", null);
		}
		return R.ok().put("materialList", materialList);
	}

	// 上传物料
	@RequestMapping("/uploadMaterial")
	public R uploadMaterial(@RequestParam Map<String, Object> params,
			HttpServletRequest request) {
		if (request.getSession().getAttribute("userId")==null) {
			return R.ok().put("result", "用户id过期，请重新登录");
		}
		long userId = (Long) request.getSession().getAttribute("userId");
		
		String refreshToken = accountController.getRefreshToken(userId);
		// 用refreshToken拿accessToken
		JSONObject jsonObject = accountController
				.getAccessTokenByRF(refreshToken);
		String accessToken = jsonObject.getString("access_token");
		String newRefreshToken = jsonObject.getString("refresh_token");
		accountController.updateRefreshToken(userId, newRefreshToken);
		if (accessToken == null) {
			return R.ok().put("error", "获取access_token失败");
		}
		String promotionPlanNamestr = (String) params.get("ppnstr");
		String promotionUnitNamestr = (String) params.get("punstr");
		String keywordstr = (String) params.get("kwstr");
		String clickRatestr = (String) params.get("crstr");
		String pricestr = (String) params.get("pricestr");
		String[] promotionPlanName = promotionPlanNamestr.split(",");
		String[] promotionUnitName = promotionUnitNamestr.split(",");
		String[] keyword = keywordstr.split(",");
		String[] clickRate = clickRatestr.split(",");
		String[] price = pricestr.split(",");

		// 遍历推广计划，查询是否存在
		long campaignId;
		long adgroupId;
		List<KeywordEntity> keywordEntity = new ArrayList<KeywordEntity>();
		// kad系统的获取的推广计划只有一个
		String campaignIdStr = campaignController.addCampaign(accessToken,
				promotionPlanName[0]);
		if (campaignIdStr == null) {
			return R.ok().put("result", "添加推广计划出错");
		}
		String adgroupIdStr = "";
		campaignId = Long.valueOf(campaignIdStr);
		List<String> uploadKeywordList = new ArrayList<String>();
		List<Double> uploadPriceList = new ArrayList<Double>();
		Map<Long, String> adgroupMap = new HashMap<Long, String>();
		List<KeywordType> keywordTypeList = new ArrayList<KeywordType>();		
		List<KeywordEntity> failuresList = new ArrayList<KeywordEntity>();
		int countUpload=0;
		for (int i = 0; i < promotionPlanName.length; i++) {
			
				if(i==0){
					adgroupIdStr = adgroupController.addAdgroup(accessToken,
							campaignId, promotionUnitName[i]);
					adgroupMap.put(Long.valueOf(adgroupIdStr), promotionUnitName[i]);
					uploadKeywordList.add(keyword[i]);
					uploadPriceList.add(Double.valueOf(price[i]));
				}else{
					if(!promotionUnitName[i].equals(promotionUnitName[i-1])){						
						JSONObject response = keywordController.addKeyword(accessToken, Long.valueOf(adgroupIdStr),uploadKeywordList, uploadPriceList);
						JSONObject headerObj =JSONObject.parseObject(response.getString("header"));
						if(headerObj.getString("failures")!=null&&!headerObj.getString("failures").isEmpty()){
						JSONArray headerArray =JSONObject.parseArray(headerObj.getString("failures"));
						for (int j = 0; j < headerArray.size(); j++){
							KeywordEntity failuresEntity = new KeywordEntity();
							String position = headerArray.getJSONObject(j).getString("position");
							long code = Long.valueOf(headerArray.getJSONObject(j).getString("code"));
							int index = Integer.valueOf(position.charAt(position.indexOf("[")+1)+"")+countUpload;
							failuresEntity.setUserId(userId);
							failuresEntity.setCampaignId(campaignId);
							failuresEntity.setCampaignName(promotionPlanName[0]);
							failuresEntity.setAdgroupId(Long.valueOf(adgroupIdStr));
							failuresEntity.setAdgroupName(adgroupMap.get(Long.valueOf(adgroupIdStr)));
							failuresEntity.setKeywordId(0);
							failuresEntity.setKeyword(keyword[index]);
							failuresEntity.setPrice(Double.valueOf(price[index]));
							failuresEntity.setStatusCode(code);
							Date createTime = new Date();
							failuresEntity.setCreateTime(createTime);
							failuresList.add(failuresEntity);						
							}
						}						
						response = JSONObject.parseObject(response.getString("body"));
						if(response.getString("data")==null||response.getString("data").isEmpty()){
							return R.error("推广账户登录失效，请重新登录"); 
						}
						countUpload = countUpload + uploadKeywordList.size();
						JSONArray keywordArray = JSONObject.parseArray(response.getString("data"));
						uploadKeywordList = new ArrayList<String>();
						uploadPriceList = new ArrayList<Double>();
						if(keywordArray!=null&&!keywordArray.isEmpty()){
						keywordTypeList.addAll(JSON.parseArray(keywordArray.toJSONString(),KeywordType.class));														
						adgroupIdStr = adgroupController.addAdgroup(accessToken,
								campaignId, promotionUnitName[i]);
						adgroupMap.put(Long.valueOf(adgroupIdStr), promotionUnitName[i]);
						}
						uploadKeywordList.add(keyword[i]);
						uploadPriceList.add(Double.valueOf(price[i]));
						
					}else{
						uploadKeywordList.add(keyword[i]);
						uploadPriceList.add(Double.valueOf(price[i]));
					}
				}
				if(i==promotionPlanName.length-1){
					JSONObject response = keywordController.addKeyword(accessToken, Long.valueOf(adgroupIdStr),uploadKeywordList, uploadPriceList);
					JSONObject headerObj =JSONObject.parseObject(response.getString("header"));
					if(headerObj.getString("failures")!=null&&!headerObj.getString("failures").isEmpty()){
					JSONArray headerArray =JSONObject.parseArray(headerObj.getString("failures"));
					
					for (int j = 0; j < headerArray.size(); j++){
						KeywordEntity failuresEntity = new KeywordEntity();
						String position = headerArray.getJSONObject(j).getString("position");
						long code = Long.valueOf(headerArray.getJSONObject(j).getString("code"));
						
						int index = Integer.valueOf(position.charAt(position.indexOf("[")+1)+"")+countUpload;
						failuresEntity.setUserId(userId);
						failuresEntity.setCampaignId(campaignId);
						failuresEntity.setCampaignName(promotionPlanName[0]);
						failuresEntity.setAdgroupId(Long.valueOf(adgroupIdStr));
						failuresEntity.setAdgroupName(adgroupMap.get(Long.valueOf(adgroupIdStr)));
						failuresEntity.setKeywordId(0);
						failuresEntity.setKeyword(keyword[index]);
						failuresEntity.setStatusCode(code);
						Date createTime = new Date();
						failuresEntity.setCreateTime(createTime);
						failuresList.add(failuresEntity);						
						}
					}
					response = JSONObject.parseObject(response.getString("body"));
					if(response.getString("data")==null||response.getString("data").isEmpty()){
						return R.error("推广账户登录失效，请重新登录"); 
					}
					JSONArray keywordArray = JSONObject.parseArray(response.getString("data"));
					if(keywordArray!=null&&!keywordArray.isEmpty()){
						keywordTypeList.addAll(JSON.parseArray(keywordArray.toJSONString(),KeywordType.class));	
					}
					//901635				
				}
			
		}
		List<KeywordEntity> keywordEntityList = new ArrayList<KeywordEntity>();
		for(KeywordType k : keywordTypeList){
			KeywordEntity entity = new KeywordEntity();
			entity.setUserId(userId);
			entity.setCampaignId(campaignId);
			entity.setCampaignName(promotionPlanName[0]);
			entity.setAdgroupId(k.getAdgroupId());
			entity.setAdgroupName(adgroupMap.get(k.getAdgroupId()));
			entity.setKeywordId(k.getKeywordId());
			entity.setKeyword(k.getKeyword());
			entity.setPrice(k.getPrice());
			entity.setStatusCode(0);
			Date createTime = new Date();
			entity.setCreateTime(createTime);
			keywordEntityList.add(entity);			
		}
		keywordEntityList.addAll(failuresList);
		keywordController.saveKeyword(keywordEntityList);
		int keywordSize = keywordTypeList.size();
		return R.ok().put("result",
				"已选择" + keyword.length + "个词,成功添加" + keywordSize + "个关键词");
	}
	
	@RequestMapping("/showMaterial")
	public R showMaterial(@RequestParam Map<String, Object> params,HttpServletRequest request){
		String promotionPlanName = (String) request.getSession().getAttribute("promotionPlanName");
		String promotionUnitName = (String) request.getSession().getAttribute("promotionUnitName");
		String keyword = (String) request.getSession().getAttribute("keyword");
		String clickRate = (String) request.getSession().getAttribute("clickRate");
		if(promotionPlanName==null||promotionUnitName==null||keyword==null){
			return R.ok().put("result", "error");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("promotionPlanName", promotionPlanName);
		map.put("promotionUnitName", promotionUnitName);
		map.put("keyword", keyword);
		map.put("clickRate", clickRate);
		return R.ok().put("result",map);		
	}
}
